package cn.edu.jcu.kyle.gintama.OurUtil;

import cn.edu.jcu.kyle.gintama.DbUtil;
import cn.edu.jcu.kyle.gintama.Main;
import cn.edu.jcu.kyle.gintama.data.COVID.COVIDData;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Objects;

public class COVIDQuery {
    private static final String url = "https://qqlykm.cn/api/yiqing/?key=XyBnErySNan5xTBJl6ga54eBtz&city=";
    private static String cityName;        //城市名称
    private static String conNum;          //累计确诊人数
    private static String deathNum;        //累计死亡人数
    private static String cureNum;         //累计治愈人数
    private static String symptomNum;      //目前新增人数
    private static String updateTime;      //数据更新时间
    private static Connection conn = null;
    private static ResultSet resultSet = null;
    private static String tmp = "";
    private static boolean flag;

    public static void Query(String _cityName) {
        createTable();      //建个表
        if (Objects.equals(_cityName, "")) {        //输入城市名为空
            Alert alert = new Alert(Alert.AlertType.WARNING);       //弹出警告窗口
            alert.setTitle("你TM犯法了你知不知道");
            alert.setHeaderText("输入为空！");
            alert.setContentText("其实输入为空应该返回全世界数据的，但我不想做");
            alert.showAndWait();
            return;
        }
        String str = HttpUtil.get(url + _cityName);     //发起http请求
        COVIDData data = JSONUtil.toBean(str, COVIDData.class); //把返回的json转成javaBean
        if (!data.getSuccess()) {                       //如果返回的json里显示请求失败
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("哦吼？");
            alert.setHeaderText("获取失败！");
            alert.setContentText("请检查是否是接口调用次数达到限制或网络连接是否畅通");
            alert.showAndWait();
            return;
        } else if (data.getData().getConNum() == null) {//如果返回的json里数据为null，说明输入有误
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("你TM犯法了你知不知道");
            alert.setHeaderText("咱有这个城市吗？");
            alert.setContentText("你看看你输了个啥东西");
            alert.showAndWait();
            return;
        }
        writeIn(data);
        if (queryInSQL(data.getData().getName())) {//查询数据库中是否已经存在查询城市的信息
            askForChoice(data);
        } else {
            show();
            wINdb();
        }
    }

    private static void askForChoice(COVIDData data) {//一个窗口，别问为什么不用fxml，fxml是坏文明
        String str = ("数据库中已存在" + data.getData().getName() + tmp + "的数据，是否更新数据库？");
        Text text = new Text(str);
        Button bt1 = new Button("是");
        bt1.setOnAction(COVIDQuery::yes);
        Button bt2 = new Button("否");
        bt2.setOnAction(COVIDQuery::no);
        HBox hBox = new HBox(bt1, bt2);
        hBox.setAlignment(Pos.BOTTOM_CENTER);
        VBox vBox = new VBox(text, hBox);
        vBox.setAlignment(Pos.TOP_CENTER);
        Scene scene = new Scene(vBox);
        Stage stage = new Stage();
        stage.setTitle("提示");
        stage.setScene(scene);
        stage.showAndWait();
    }

    public static void yes(ActionEvent actionEvent) {//选择要更新数据库信息后，展示新获取的信息并写入数据库
        ((Node) (actionEvent.getSource())).getScene().getWindow().hide();
        show();
        wINdb();
    }

    public static void no(ActionEvent actionEvent) {//选择不更新数据库信息之后，展示数据库里的信息和获取到的新信息
        ((Node) (actionEvent.getSource())).getScene().getWindow().hide();
        showWithDb();
        show();
    }

    private static boolean queryInSQL(String _cityName) {//查询搜索数据是否在数据库里存在
        try {
            conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
            String str = "select * from COVID_Data where CityName='" + _cityName + "'";
            resultSet = DbUtil.executeQuery(conn, str);
            if (resultSet.next()) {//判断是否存在
                tmp = resultSet.getString("UpdateTime");
                flag = true;
                return true;
            } else {
                flag = false;
                return false;
            }
        } catch (Exception e) {
            System.out.println("报错");
            e.printStackTrace();
            return false;
        }
    }

    private static void writeIn(COVIDData data) {//你就当构造函数
        cityName = data.getData().getName();
        conNum = data.getData().getConNum();
        deathNum = data.getData().getDeathNum();
        cureNum = data.getData().getCureNum().split("\"")[0];
        symptomNum = data.getData().getAsymptomNum();
        updateTime = data.getData().getUpdateTime();
    }

    private static void show() {//展示当前搜索数据
        ListView<String> listView = new ListView<>();   //创建一个列表控件
        ObservableList<String> dataList = FXCollections.observableArrayList(
                updateTime + "," + cityName + "市的疫情数据",
                "累计确诊：" + conNum,
                "累计死亡：" + deathNum,
                "累计治愈：" + cureNum,
                "新增人数：" + symptomNum);       //列表显示数据
        listView.setItems(dataList);
        Stage stage = new Stage();              //创建一个新窗口
        stage.setTitle(cityName + "市疫情数据"); //新窗口的标题
        stage.getIcons().add(new Image(Objects.requireNonNull(Main.class.getResource("img/virus.png")).toExternalForm()));  //新窗口图标
        stage.setHeight(250);                   //新窗口高度
        stage.setWidth(300);                    //新窗口宽度
        stage.setScene(new Scene(listView));    //这个窗口里边装着上边那个列表控件
        stage.show();                           //弹出新窗口
    }

    private static void showWithDb() {//展示数据库里的数据
        ListView<String> listViewDb = new ListView<>();   //创建一个列表控件
        ObservableList<String> dataList = null;
        try {
            dataList = FXCollections.observableArrayList(
                    resultSet.getString("UpdateTime") +
                            "," +
                            resultSet.getString("CityName") +
                            "市的疫情数据",
                    "累计确诊：" + resultSet.getString("ConNum"),
                    "累计死亡：" + resultSet.getString("DeathNum"),
                    "累计治愈：" + resultSet.getString("CureNum"),
                    "新增人数：" + resultSet.getString("SymptomNum"));
        } catch (Exception e) {
            e.printStackTrace();
            AlertWindow.getWindow("警告！发生错误！");
            System.exit(-1);
        }
        listViewDb.setItems(dataList);
        Stage stageDb = new Stage();
        stageDb.setTitle("数据库中" + cityName + "市疫情数据");
        stageDb.getIcons().add(new Image(Objects.requireNonNull(Main.class.getResource("img/virus.png")).toExternalForm()));  //新窗口图标
        stageDb.setHeight(250);
        stageDb.setWidth(300);
        stageDb.setScene(new Scene(listViewDb));
        stageDb.show();
    }

    private static void wINdb() {//写入数据库
        if (!flag) {//如果数据库中没有城市的数据，使用插入语句
            try {
                conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String insertSQL = "insert into COVID_Data (CityName, ConNum, DeathNum, CureNum, SymptomNum, UpdateTime) values (?, ?, ?, ?, ?, ?)";
            Object[] paramsInsert = {cityName, conNum, deathNum, cureNum, symptomNum, updateTime};
            DbUtil.executeUpdate(conn, insertSQL, paramsInsert);
        } else {//如果有，使用更新语句
            try {
                conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String insertSQL = "update COVID_Data set ConNum=?, DeathNum=?, CureNum=?, SymptomNum=?, UpdateTime=? where CityName=?";
            Object[] paramsInsert = {conNum, deathNum, cureNum, symptomNum, updateTime, cityName};
            DbUtil.executeUpdate(conn, insertSQL, paramsInsert);
        }
    }

    private static void createTable() {//建个表
        String createTable = """
                create table if not exists gintama.COVID_Data
                (
                    CityName   varchar(60) not null comment '城市名',
                    ConNum     varchar(60) not null comment '确诊人数',
                    DeathNum   varchar(60) not null comment '死亡人数',
                    CureNum    varchar(60) not null comment '治愈人数',
                    SymptomNum varchar(60) not null comment '新增人数',
                    UpdateTime varchar(60) not null comment '该数据更新时间',
                    constraint COVID_Data_pk
                        primary key (CityName)
                )""";
        try {
            conn = DbUtil.getMySQLConnection("jdbc:mysql://localhost:3306/gintama?useUnicode=utf8&useSSL=false");
            DbUtil.executeUpdate(conn, createTable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
